import React, { useState, useEffect, useCallback } from 'react';
import { Table, Spin, Alert, Pagination, Input, Space, Button, Tag, message } from 'antd';
import { SearchOutlined, CheckCircleOutlined } from '@ant-design/icons';
import type { ColumnsType, TableProps } from 'antd/es/table';
import http from '../api/http';
import type { IATjsc, Itjsc } from '../types/tjsc';
import { Add } from './add';

// 报告状态映射
const reportStatusMap = {
  1: { text: '体检完成', color: 'green' },
  0: { text: '准备体检', color: 'orange' }
};

export default function Exm() {
  // 状态管理
  const [data, setData] = useState<Itjsc[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);
  const [searchPhone, setSearchPhone] = useState<string>('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 3,
    total: 0
  });
  const [operatingId, setOperatingId] = useState<number | null>(null); // 记录当前操作的ID，用于控制按钮加载状态

  // 数据请求函数
  const fetchExamData = useCallback(async () => {
    const { current, pageSize } = pagination;
    try {
      setLoading(true);
      setError(null);
      
      const params = new URLSearchParams();
      params.append('page', current.toString());
      params.append('size', pageSize.toString());
      if (searchPhone.trim()) {
        params.append('phone', searchPhone.trim());
      }
      
      const response: IATjsc = await http.getList<Array<IATjsc>>("Mexam", params);
      setData(response.data || []);
      setPagination(prev => ({ ...prev, total: response.count || 0 }));
    } catch (err) {
      setError('数据加载失败，请稍后重试');
      console.error('接口请求错误:', err);
    } finally {
      setLoading(false);
    }
  }, [pagination.current, pagination.pageSize, searchPhone]);

  // 初始加载数据
  useEffect(() => {
    fetchExamData();
  }, [fetchExamData]);

 // 新增弹窗控制状态
const [addModalVisible, setAddModalVisible] = useState<boolean>(false); // 控制弹窗显示
const [currentRecord, setCurrentRecord] = useState<Itjsc | null>(null); // 存储当前点击的记录数据

  // 分页变化处理
  const handlePaginationChange = (current: number, pageSize: number) => {
    setPagination({ current, pageSize });
  };

  // 搜索处理
  const handleSearch = () => {
    
    console.log("嘿嘿")
    setPagination(prev => ({ ...prev, current: 1 }));
      fetchExamData();
      
  };

  // 回车键触发搜索
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSearch();
    }
  };

  // 清除搜索条件
  const handleClearSearch = () => {
    if (searchPhone) {
      setSearchPhone('');
      setPagination(prev => ({ ...prev, current: 1 }));
    }
  };

  // 表格列配置（新增操作列）
  const columns: ColumnsType<Itjsc> = [
    {
      title: '记录ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '档案编号',
      dataIndex: 'fileNumber',
      key: 'fileNumber',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '手机号',
      dataIndex: 'phoneNumber',
      key: 'phoneNumber',
      render: (phone: string) => phone || '-',
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
      key: 'idCard',
      render: (idCard: string) => idCard.length === 18 
        ? `${idCard.slice(0, 6)}********${idCard.slice(14)}` 
        : idCard || '-',
    },
    {
      title: '套餐名称',
      dataIndex: 'sname',
      key: 'sname',
      ellipsis: { showTitle: false },
    },
    {
      title: '检查时间',
      dataIndex: 'examdate',
      key: 'examdate',
      render: (date: string) => date ? new Date(date).toLocaleString('zh-CN', { 
        year: 'numeric', month: '2-digit', day: '2-digit', 
        hour: '2-digit', minute: '2-digit' 
      }) : '-',
    },
    {
      title: '体检状态',
      dataIndex: 'reportstatus',
      key: 'reportstatus',
      render: (status: number) => {
        const statusInfo = reportStatusMap[status as keyof typeof reportStatusMap] || 
                          { text: '未知', color: 'gray' };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      },
    },
    // 新增操作列
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_: any, record: Itjsc) => (
        <Button
          type={record.reportstatus === 1 ? 'default' : 'primary'}
          size="small"
          loading={operatingId === record.id}
          disabled={record.reportstatus === 1}
          onClick={() =>{
        setCurrentRecord(record); // 把当前行数据传给弹窗
        setAddModalVisible(true); // 显示弹窗
      }}
          icon={<CheckCircleOutlined />}
        >
          {record.reportstatus === 1 ? '已完成' : '体检'}
        </Button>
      ),
    },
  ];

  const tableProps: TableProps<Itjsc> = {
    dataSource: data,
    columns,
    rowKey: 'id',
    bordered: true,
    pagination: false,
    scroll: { x: 1450 }, // 调整横向滚动宽度以适应新列
    size: 'middle',
    loading: loading,
    locale: { emptyText: '暂无匹配数据' },
  };

  if (error) {
    return (
      <Alert
        message="数据加载失败"
        description={error}
        type="error"
        showIcon
        style={{ margin: '20px' }}
        action={<Button onClick={fetchExamData} type="text" danger>重试</Button>}
      />
    );
  }

  return (
    <div style={{ padding: '20px', background: '#fff' }}>
      <h2 style={{ marginBottom: '16px' }}>检查记录管理</h2>
      
      {/* 搜索区域 */}
      <Space style={{ marginBottom: '16px' }}>
        <Input
          placeholder="请输入手机号模糊查询"
          value={searchPhone}
          onChange={(e) => setSearchPhone(e.target.value)}
          onKeyPress={handleKeyPress}
          style={{ width: 300 }}
          prefix={<SearchOutlined />}
        />
        <Button type="primary" onClick={handleSearch}>搜索</Button>
        <Button onClick={handleClearSearch}>清除</Button>
      </Space>
      
      {/* 表格主体 */}
      <Table {...tableProps} />
      
      {/* 分页组件 */}
      <div style={{ marginTop: '16px', textAlign: 'right' }}>
        <Pagination
          current={pagination.current}
          pageSize={pagination.pageSize}
          total={pagination.total}
          onChange={handlePaginationChange}
          showSizeChanger
          showTotal={(total) => `共 ${total} 条记录`}
          pageSizeOptions={['3', '5', '10']}
        />
      </div>
      
  <Add
  visible={addModalVisible} // 控制弹窗显示/隐藏
  onCancel={() => setAddModalVisible(false)} // 弹窗关闭按钮的回调
  currentRecord={currentRecord} // 传递当前点击的记录数据（供弹窗使用）
   onSuccess={handleSearch}
/>
    </div>
  );
}